package com.zn.opit.videoframe.service.impl;

import com.zn.opit.videoframe.config.ExtMinioClient;
import com.zn.opit.videoframe.config.ExtMinioClientConfig;
import com.zn.opit.videoframe.service.MinioService;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.UUID;

@Slf4j
@Service
public class MinioServiceImpl implements MinioService {

    @Value("${spring.application.name}")
    private String applicationName;

    @Resource
    private ExtMinioClient minioClient;

    @Resource
    private ExtMinioClientConfig minIoClientConfig;

    @Override
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new RuntimeException();
        }
        String fileName = UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = applicationName + File.separator + fileName;
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minIoClientConfig.getBucketName()).object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            log.error("minio upload failed", e);
            return null;
        }
        return fileName;
    }
}
